package com.sd.activity;

import java.util.ArrayList;
import java.util.Vector;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView.OnEditorActionListener;

import com.alex.books.BaseBook;
import com.alex.books.BookStore;
import com.mobclick.android.MobclickAgent;
import com.sd.reader.ReaderSet;
import com.sd.util.BookCabin;
import com.sd.util.LoadingProgressDialog;
import com.sd.view.BookListAdapter;
import com.sd.view.BookTilingAdapter;
import com.sd.view.DialogManager;
import com.sd.view.ShelvesView;
import com.sd.view.ToastManager;

/**
 * 
 * 书籍列表
 * 
 * @author Alex.Lu
 * 
 */
public class BetaReadActivity extends BaseActivity implements OnClickListener, OnCheckedChangeListener,OnLongClickListener, OnItemClickListener, OnItemLongClickListener, TextWatcher, OnEditorActionListener {

	private static final int REQUEST_EX = 1;
	
	/**
	 * 书本的列表
	 **/
	private ListView mBooksLV;
	private ShelvesView mBooksGV;
	private BaseAdapter mBookAdapter;
	private Button mCancelBT;
	/**
	 * 书本的展现模式 
	 */
	private CheckBox mTilingModeBT;
	/**
	 * 增加书本
	 */
	private ImageButton mAddBook;
	private EditText mSearchET;
	private ImageButton mSearchBT;
	private Vector<BaseBook> mBooks;
	
	
	private Handler mHandler =  new Handler() { 
		public void handleMessage(Message msg) {  
			LoadingProgressDialog.dismiss();
            mBookAdapter.notifyDataSetChanged();
            super.handleMessage(msg);   
       }   
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		ReaderSet.getInstance().init(this);
		
		mBooksLV = (ListView)findViewById(R.id.books);
		mBooksGV = (ShelvesView)findViewById(R.id.gvbooks);
		mBooksGV.setOnItemClickListener(this);
		mBooksGV.setOnItemLongClickListener(this);
		mBooks = new Vector<BaseBook>();
		
		mCancelBT = (Button)findViewById(R.id.nosreach);
		mCancelBT.setOnClickListener(this);
		mCancelBT.setVisibility(View.GONE);
		
		mSearchET = (EditText)findViewById(R.id.search_et);
		mSearchET.addTextChangedListener(this);
		mSearchET.setOnEditorActionListener(this);
		mSearchBT = (ImageButton)findViewById(R.id.search_btn);
		mSearchBT.setOnClickListener(this);
		
		mBookAdapter = new BookTilingAdapter(this,mBooks,this,this);
		mBooksGV.setAdapter(mBookAdapter);
		mTilingModeBT = (CheckBox) findViewById(R.id.tiling_mode);
		mTilingModeBT.setOnCheckedChangeListener(this);
		
		mAddBook = (ImageButton)findViewById(R.id.add_book);
		mAddBook.setOnClickListener(this);
		
		LoadingProgressDialog.show(this, R.string.msg_loading);
		new Thread(new mThread()).start();
		
		
		MobclickAgent.setAutoLocation(false);
//		MobclickAgent.setSessionContinueMillis(10000);
		MobclickAgent.setUpdateOnlyWifi(false);
		
		MobclickAgent.update(this);
		MobclickAgent.onError(this);
		MobclickAgent.updateOnlineConfig(this);
	}

	
	
	/**
	 * 是否退出客户端的对话框
	 */
	public void createExitDialog() {
		Builder builder = new AlertDialog.Builder(this);
		
		builder.setMessage(getString(R.string.msg_exit)).setPositiveButton(
				R.string.btn_ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						System.exit(0);
					}
				}).setNegativeButton(R.string.btn_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				}).show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int bookid;
		int v_id = v.getId();
		Intent intent = new Intent();
		switch (v_id) {
		case R.id.nosreach:
			InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
			mCancelBT.setVisibility(View.GONE);
			mSearchET.setText("");
			mSearchET.clearFocus();
			Vector<BaseBook> tempBooks1 = BookCabin.getInstance().getBooks(BetaReadActivity.this,"");
			mBooks.clear();
			for(int i=0;i<tempBooks1.size();i++){
				mBooks.add(tempBooks1.get(i));
			}
			mBookAdapter.notifyDataSetChanged();
			break;
		case R.id.book1:
			DialogManager.getInstance().dismiss();
		case R.id.text:
			int bookId = (Integer)v.getTag();
			BaseBook book1 = BookStore.getInstance().getABook(BetaReadActivity.this, bookId);
			if(book1.mBookPath.endsWith(".sbn") || book1.mBookPath.endsWith(".txt") || book1.mBookPath.endsWith(".umd") || book1.mBookPath.endsWith(".epub")){
				intent.putExtra(ReadBookActivity.BOOK_ID, book1.mBookId);
				intent.setClass(this, ReadBookActivity.class);
				startActivity(intent);
			}else{
				Toast.makeText(BetaReadActivity.this, R.string.msg_format_does_not_support, Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.add_book:
			if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
				intent.setClass(this, FilesActivity.class);
				startActivityForResult(intent, REQUEST_EX);
			}else{
				ToastManager.getInstance().showText(this, R.string.msg_error_no_storage);
			}
			break;
		case R.id.search_btn:
			mSearchET.clearFocus();
			imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
			String text = mSearchET.getText().toString();
			if(text.equals("")){
				text = null;
			}
			Vector<BaseBook> tempBooks = BookCabin.getInstance().getBooks(BetaReadActivity.this,text);
			mBooks.clear();
			for(int i=0;i<tempBooks.size();i++){
				mBooks.add(tempBooks.get(i));
			}
			 mBookAdapter.notifyDataSetChanged();
			break;
			/**
			 * 阅读设置
			 */
		case R.id.add_book_bt:
			//增加书本
			intent.setClass(this, FilesActivity.class);
			startActivityForResult(intent, REQUEST_EX);
			DialogManager.getInstance().dismiss();
			break;
		case R.id.book_delete_bt:
			//删除书本
			DialogManager.getInstance().dismiss();
			BaseBook book =null;
			bookid = (Integer)v.getTag();
			for(int i=0;i<mBooks.size();i++){
				book = mBooks.get(i);
				if(book.mBookId == bookid){
					break;
				}
			}
			if(book==null )
				return ;
			
			if(book.mAttach1 !=null && book.mAttach1.equals("1")){
				ToastManager.getInstance().showText(this, R.string.msg_system_book);
			}else{

				boolean flag =BookCabin.getInstance().removeBook(this, book);
				if(flag){
					mBooks.removeElement(book);
					mBookAdapter.notifyDataSetChanged();
				}
			}
			
			break;
		case R.id.read_set_bt:
			//阅读设置
			
			startActivity(ReadSetActivity.BookshelfTo(this));
			DialogManager.getInstance().dismiss();
			break;
		case R.id.clean_bt:
			DialogManager.getInstance().dismiss();
			cleanAllbooks();
			break;
		case R.id.bookmark_bt:
			//书本的标签
			bookid = (Integer)v.getTag();
			DialogManager.getInstance().dismiss();
			startActivity(BookInfoActivity.getBookMark(this,bookid));
			break;
		case R.id.bookinfo_bt:
			//书本信息
			bookid = (Integer)v.getTag();
			DialogManager.getInstance().dismiss();
			startActivity(BookInfoActivity.getBookInfo(this,bookid));
			break;
		case R.id.book_catalogue_bt:
			//书本目录
			bookid = (Integer)v.getTag();
			DialogManager.getInstance().dismiss();
			startActivity(BookInfoActivity.getBookContents(this,bookid));
			break;
		case R.id.contiune_read_bt:
			//继续阅读
			bookId = (Integer)v.getTag();
			intent.putExtra(ReadBookActivity.BOOK_ID, bookId);
			intent.setClass(this, ReadBookActivity.class);
			startActivity(intent);
			DialogManager.getInstance().dismiss();
			break;
		default:
			break;
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if(isChecked==true){
			mBookAdapter = new BookListAdapter(this,mBooks);
			mBooksLV.setVisibility(View.VISIBLE);
			mBooksGV.setVisibility(View.GONE);
			mBooksLV.setAdapter(mBookAdapter);
			mBooksLV.setOnItemClickListener(this);
			mBooksLV.setOnItemLongClickListener(this);
		}else{
			mBookAdapter = new BookTilingAdapter(this,mBooks,this,this);
			mBooksGV.setVisibility(View.VISIBLE);
			mBooksLV.setVisibility(View.GONE);
			mBooksGV.setAdapter(mBookAdapter);
			mBooksGV.setOnItemClickListener(this);
			mBooksGV.setOnItemLongClickListener(this);
		}
	}
	
   

	@Override
	public boolean onLongClick(View v) {
		// TODO Auto-generated method stub
		int bookId = (Integer)v.getTag();
		DialogManager.getInstance().createReaderSet(this, this,bookId);
		return false;
	}
	
	
	private class mThread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Vector<BaseBook> tempBooks = BookCabin.getInstance().getBooks(BetaReadActivity.this,null);
			mBooks.clear();
			for(int i=0;i<tempBooks.size();i++){
				mBooks.add(tempBooks.get(i));
			}
			
			mHandler.sendEmptyMessage(0);
		}
	}
 
	/*************
	 * 清楚所有书籍
	 */
	private void cleanAllbooks(){
		LoadingProgressDialog.show(this, R.string.msg_clean_all);
		Vector<BaseBook> tempdeletebooks = new Vector<BaseBook>();
		for(int i=0;i<mBooks.size();i++){
			BaseBook book = mBooks.get(i);
			if(book.mAttach1!=null &&  book.mAttach1.equals("1")){
			}else{
				BookStore.getInstance().deleteBook(this, mBooks.get(i));
				tempdeletebooks.add(mBooks.get(i));
			}
		}
		Vector<BaseBook> tempBooks = BookCabin.getInstance().getBooks(BetaReadActivity.this,null);
		mBooks.clear();
		for(int i=0;i<tempBooks.size();i++){
			mBooks.add(tempBooks.get(i));
		}
		mBookAdapter.notifyDataSetChanged();
		LoadingProgressDialog.dismiss();
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		BaseBook book = (BaseBook)parent.getItemAtPosition(position);
		if(book.mBookPath.endsWith(".sbn") ||book.mBookPath.endsWith(".txt") || book.mBookPath.endsWith(".umd") || book.mBookPath.endsWith(".epub")){
			Intent intent = new Intent(); 
			intent.putExtra(ReadBookActivity.BOOK_ID, book.mBookId);
			intent.setClass(this, ReadBookActivity.class);
			startActivity(intent);
		}else{
			Toast.makeText(BetaReadActivity.this, R.string.msg_format_does_not_support, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		// TODO Auto-generated method stub
		BaseBook book = (BaseBook)parent.getItemAtPosition(position);
		DialogManager.getInstance().createReaderSet(this, this,book.mBookId);
		return false;
	}
	
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		return imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
	}



	/*************************************************************
	 * 搜索框今天
	 **************************************************************/
	@Override
	public void afterTextChanged(Editable s) {
		if(s != null&& s.toString().equals("")){
			mCancelBT.setVisibility(View.GONE);
		}else{
			mCancelBT.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}

	
	/*********************************************************
	 * activity override
	 ********************************************************/
	@Override
	public void onBackPressed() {
		createExitDialog();
	}
	
	@Override
	protected void onRestart() {
		Vector<BaseBook> tempBooks1 = BookCabin.getInstance().getBooks(BetaReadActivity.this,"");
		mBooks.clear();
		for(int i=0;i<tempBooks1.size();i++){
			mBooks.add(tempBooks1.get(i));
		}
		mBookAdapter.notifyDataSetChanged();
		super.onRestart();
	}


	@Override
	protected void onStart() {
		super.onStart();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	 protected void onActivityResult(int requestCode, int resultCode,
				Intent intent) {
			if (resultCode == RESULT_OK) {
				if (requestCode == REQUEST_EX) {
					ArrayList<String> uri = intent.getStringArrayListExtra("EEE");
					/*		
					for(int i=0;i<uri.size();i++){
						String url = uri.get(i);
						if(!isHashBook(url)){
							BaseBook book = new BaseBook();
							book.mBookName =url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."));
							book.mBookPath = url;
							book.mBookId = (int)BookDao.getInstance().insertBook(this, book);
							BookCabin.getInstance().realAddBook(book);
							mBooks.add(book);
						}
					}*/
		        	mBookAdapter.notifyDataSetChanged();
				}
			}
		}



	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		// TODO Auto-generated method stub
		switch(actionId){  
        case EditorInfo.IME_ACTION_SEARCH:
        	InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        	mSearchET.clearFocus();
			imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
			String text = mSearchET.getText().toString();
			if(text.equals("")){
				text = null;
			}
			Vector<BaseBook> tempBooks = BookCabin.getInstance().getBooks(BetaReadActivity.this,text);
			mBooks.clear();
			for(int i=0;i<tempBooks.size();i++){
				mBooks.add(tempBooks.get(i));
			}
			 mBookAdapter.notifyDataSetChanged();
            break;  
        }  
		return false;
	}


}